package thread;

// 实现一个阻塞队列
// 不考虑泛型, 使用 int 来表示元素
class MyBlockingQueue {
    private int[] items = new int[1000];
    private int head = 0;
    private int tail = 0;
    private int size = 0;

    // 入队列
    public synchronized void put(int val) throws InterruptedException {
        while (size == items.length) {
            // 队列满了, 要产生阻塞
            // return;
            this.wait();
        }
        items[tail] = val;
        tail++;
        // 针对 tail 的处理
        // 1)
        // tail = tail % items.length;
        // 2)
        if (tail >= items.length) {
            tail = 0;
        }
        size++;

        // 唤醒 take 中的 wait
        this.notify();
    }

    // 出队列
    public synchronized Integer take() throws InterruptedException {
        while (size == 0) {
            // 队列空
            // return null;
            this.wait();
        }
        int res = items[head];
        head++;
        if (head >= items.length) {
            head = 0;
        }
        size--;

        // 唤醒 put 中的wait
        this.notify();
        return res;
    }
}

public class ThreadDemo23 {
    public static void main(String[] args) throws InterruptedException {
//        MyBlockingQueue queue = new MyBlockingQueue();
//
//        queue.put(1);
//        queue.put(2);
//        queue.put(3);
//        queue.put(4);
//        int res = 0;
//        System.out.println(queue.take());
//        System.out.println(queue.take());
//        System.out.println(queue.take());
//        System.out.println(queue.take());

        MyBlockingQueue queue = new MyBlockingQueue();

        Thread customer = new Thread(() -> {
            while (true) {
                try {
                    int res = queue.take();
                    System.out.println("消费元素: " + res);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        customer.start();

        Thread producer = new Thread(() -> {
            int count = 0;
            while (true) {
                try {
                    System.out.println("生产元素: " + count);
                    queue.put(count);
                    count++;
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        producer.start();
    }
}
